package org.ehe.business.overdue.service.ove;

import lombok.extern.slf4j.Slf4j;
import org.ehe.business.overdue.config.OverdueStatus;
import org.ehe.business.overdue.domain.OverdueRecord;
import org.ehe.business.overdue.mapper.OverdueRecordMapper;
import org.ehe.business.overdue.queue.RedisDelayQueue;
import org.ehe.business.timeout.contants.BizTypeConstant;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 超时延期处理Service
 * @author :zhangnn
 * @className :OverdueDelayService
 * @description: TODO
 * @date 2025-10-17 10:05:19
 */
@Slf4j
@Service
public class OverdueDelayService {

    @Autowired
    private OverdueRecordMapper overdueRecordMapper;
    @Autowired
    private RedisDelayQueue delayQueue;

    public void delay(String bizType,Long bizId){
        log.info("进入超时延期方法bizType={},bizId={}",bizType,bizId);
        OverdueRecord overdue = overdueRecordMapper.selectByBizTypeAndId(bizType,bizId);
        if(Objects.nonNull(overdue) &&  (overdue.getHandleStatus() == 0 || overdue.getHandleStatus() == 3)){
            delayQueue.removeTask(overdue.getBizType(),overdue.getBizId());
            OverdueRecord newOverdue = new OverdueRecord();
            BeanUtils.copyProperties(overdue,newOverdue);
            //超期未处理
            newOverdue.setHandleStatus(Integer.valueOf(OverdueStatus.OVERDUE_AND_PENDING));
            //已经提醒
            newOverdue.setDeadlineStatus(OverdueStatus.DEADLINE_STATUS_1);
            //延迟1小时再次推送
            newOverdue.setDeadlineTime(LocalDateTime.now().plusHours(1));
            newOverdue.setCount(overdue.getCount() +1);
            if(newOverdue.getCount() < 3){
                overdueRecordMapper.insertOrUpdate(newOverdue);
                log.info("加入新的超期提醒信息bizId={},截止时间",overdue.getBizId(),newOverdue.getDeadlineTime());
                delayQueue.addTask(overdue.getBizType(), overdue.getBizId(), newOverdue.getDeadlineTime());
            }
            //添加提醒记录
            overdueRecordMapper.insertHistory(overdue);
        }
    }

    /**
     * 提醒状态修改
     * @param bizType
     * @param bizId
     */
    public void remind(String bizType,Long bizId){
        OverdueRecord overdue = overdueRecordMapper.selectByBizTypeAndId(bizType,bizId);
        if(Objects.nonNull(overdue)){
            overdue.setRemindStatus(OverdueStatus.REMIND_STATUS_1);//已经提醒
            overdueRecordMapper.insertOrUpdate(overdue);
        }
    }
}
